package com.zsw.upload;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.stream.ChunkedNioFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientHandler extends ChannelInboundHandlerAdapter {
	
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf b = (ByteBuf)msg;
		LOG.info(b.readInt() + "");
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		LOG.info("客户端连接服务器，开始发送数据……");
		ByteBuf bf = ctx.alloc().buffer();
        File file = new File("d://00.jpg");
        String str = "{\"type\":\"0\",\"length\":\""+ file.length() + "\",\"startD\":\"0\","
        		+ "\"startC\":\"0\",\"size\":\"1024\",\"MD5\":\""+getMD5(file) + "\","
        		+ "\"args\":{\"year\":\"2017\",\"billCode\":\"000000017031300000622\",\"imageType\":\"1\"}}";
        bf.writeBytes((new String(Base64.getEncoder().encode(str.getBytes()))+"\n").getBytes());
        ctx.writeAndFlush(bf);
		ChunkedNioFile ff;
		try {
			ff = new ChunkedNioFile(file);
			ctx.writeAndFlush(ff);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static String getMD5(File file) {
        MessageDigest digest = null;
        FileInputStream in;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) > 0) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (NoSuchAlgorithmException ex) {
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        } finally {
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		LOG.info("客户端断开服务器");
	}
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		LOG.info("channelReadComplete");
	}
}
